<script setup lang='ts'>
import type { VxePagerEvents } from 'vxe-table'

import { MemberTagPage, memberSelect, memberUpdateTag } from '@fl/api/anjutong'

type TagType = {
    id: string
    name: string
}
const props = defineProps(['id'])
const emits = defineEmits(['close', 'submit'])
const tableRef = ref()
const { id } = toRefs(props)
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const gridOptions = reactive({
    align: 'center',
    border: true,
    checkboxConfig: {
        range: false,
        reserve: true,
    },
    columnConfig: {
        resizable: true,
    },
    columns: [
        { type: 'checkbox', width: 50 },
        { field: 'name', title: '标签名称' },
        { field: 'mainCat', title: '一级分类' },
        { field: 'subCat', title: '二级分类' },
        { field: 'subCat', title: '说明' },
        { field: 'status', slots: { default: 'status' }, title: '状态' },
        { field: 'lastUpdateTime', title: '最后修改时间' },
    ],
    data: [],
    height: 530,
    loading: false,
    rowConfig: {
        keyField: 'id',
    },
})
const prevSelectedRows = ref<TagType[]>([]) // 用于记录上一次的勾选数据
const textarea = ref('')
const newMemberTagList = ref<TagType[]>([])
const formData = ref({
    nameTap: '',
    typeTag: 1,
})
watch(() => newMemberTagList, findIndexes, { deep: true, immediate: true })
watch(() => gridOptions.data, findIndexes, { deep: true, immediate: true })
function findIndexes() {
    const indexes = [] as any
    gridOptions.data.forEach((itemB: TagType, index) => {
        if (newMemberTagList.value.some((itemA: TagType) => itemA.id === itemB.id))
            indexes.push(gridOptions.data[index])
    })
    const $table = tableRef.value
    if ($table) {
        $table.clearCheckboxRow()
        $table.setCheckboxRow(indexes, true)
    }
}
// const TagCatList = ref<any>([])
const columns = reactive(
    [
        {
            label: '标签类型',
            options: [
                {
                    label: '手动标签',
                    value: 1,
                },
                {
                    label: '自动标签',
                    value: 0,
                },
            ],
            prop: 'typeTag',
            valueType: 'select',
            width: 300,
        },
        {
            label: '标签名称',
            prop: 'nameTap',
            valueType: 'copy',
            width: 300,
        },
    ],
)
async function findList() {
    gridOptions.loading = true
    try {
        const options = {
            mainCat: '',
            mainCats: ['基础属性', '行为属性', '偏好属性'],
            page: tablePage.currentPage,
            size: tablePage.pageSize,
            sort: '',
            subCat: '',
            tagName: formData.value.nameTap,
            type: formData.value.typeTag,
        }
        const data = await MemberTagPage(options)
        tablePage.total = data?.total ?? 0
        gridOptions.data = data?.records ?? []
    }
    catch (error) {
    }
    finally {
        gridOptions.loading = false
    }
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    findList()
}

function closeTag(id: string) {
    newMemberTagList.value = newMemberTagList.value.filter(item => item.id !== id)
}
function queryTag() {
    tablePage.currentPage = 1
    findList()
}
function resetConditions() {
    formData.value = { nameTap: '', typeTag: 1 }
    tablePage.currentPage = 1
    findList()
}
async function getMemberSelect() {
    try {
        const data = await memberSelect(id?.value)
        newMemberTagList.value = prevSelectedRows.value = data ?? []
    }
    catch (error) {
    }
}
function selectChangeEvent({ checked, records }) {
    console.log('🚀 ~ selectChangeEvent ~ checked:', checked)
    if (checked)
        prevSelectedRows.value.push(...records)

    else
        prevSelectedRows.value = prevSelectedRows.value.filter(prevRow => !(!records.some(row => row.id === prevRow.id) && gridOptions.data.some((row: TagType) => row.id === prevRow.id)))

    console.log(prevSelectedRows.value)
    newMemberTagList.value = prevSelectedRows.value.filter((obj, index, self) =>
        index === self.findIndex(t => (
            t.id === obj.id
        )),
    )
}
function editTag() {
    const params = {
        memberId: id?.value,
        memberIdList: newMemberTagList.value.map((item: TagType) => item.id),
    }
    memberUpdateTag(params).then((res: any) => {
        console.log(res, '是否添加成功')
        emits('submit')
    })
}
onMounted(() => {
    getMemberSelect().then(() => {
        findList()
    })
})
</script>

<template>
    <div style="max-width:1100px;max-height:90px;overflow-y:auto"
         absolute
         left-36
         top-90
         z-1
         flex
         flex-wrap
    >
        <div v-for="tag in newMemberTagList"
             :key="tag.name"

             mb-6
             mr-10
        >
            <el-button ml-10
                       type="primary"
                       size="small"
            >
                {{ tag.name }}<el-icon ml-6
                                       @click="closeTag(tag.id)"
                >
                    <CircleCloseFilled />
                </el-icon>
            </el-button>
        </div>
    </div>

    <el-input v-model="textarea"
              w-2400
              :rows="4"
              type="textarea"
              placeholder=""
    />

    <div mt-40
         flex
         justify-between
    >
        <PlusForm v-model="formData"
                  :columns="columns"
                  :row-props="{ gutter: 20 }"
                  :col-props="{
                      span: 12,
                  }"
                  :has-footer="false"
                  style="width:60%"
        />

        <div style="width:20%"
             flex
             justify-end
        >
            <div>
                <el-button type="primary"
                           class="mr-10"
                           @click="queryTag"
                >
                    查询
                </el-button>
            </div>

            <div>
                <el-button @click="resetConditions">
                    重置
                </el-button>
            </div>
        </div>
    </div>

    <vxe-grid v-bind="gridOptions"
              ref="tableRef"
              @checkbox-change="selectChangeEvent"
              @checkbox-all="selectChangeEvent"
    >
        <template #status="{ row }">
            <vxe-switch :model-value="row.status === 1"
                        disabled
            />
        </template>

        <template #pager>
            <!-- 使用 pager 插槽 -->
            <vxe-pager v-model:current-page="tablePage.currentPage"
                       v-model:page-size="tablePage.pageSize"
                       :layouts="['Home', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
                       :total="tablePage.total"
                       background
                       @page-change="handlePageChange"
            />
        </template>
    </vxe-grid>

    <div class="flex justify-end mt-10">
        <el-button @click="emits('close')">
            取消
        </el-button>

        <el-button type="primary"
                   @click="editTag"
        >
            确认
        </el-button>
    </div>
</template>
